package com.sl.au.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Account;
import com.sl.au.entity.AfterSaleOutHouse;
import com.sl.au.entity.AfterSaleTicket;
import com.sl.au.entity.AfterSaleTicketAdvice;
import com.sl.au.entity.AfterSaleTicketBack;
import com.sl.au.entity.AfterSaleTicketPay;
import com.sl.au.entity.User;
import com.sl.au.service.AccountService;
import com.sl.au.service.ActivitiService;
import com.sl.au.service.AfterSaleInHouseService;
import com.sl.au.service.AfterSaleOutHouseService;
import com.sl.au.service.AfterSaleTicketService;
import com.sl.au.service.AuditNodeService;
import com.sl.au.service.UserService;

/*
 * 售后内勤
 */

@RestController
@RequestMapping(value = "/ui/afterSaleInHouse")
public class AfterSaleInHouseController extends BaseController {

	@Autowired
	AfterSaleInHouseService afterSaleInHouseService;

	@Autowired
	AfterSaleTicketService afterSaleTicketService;

	@Autowired
	UserService userService;
	@Autowired
	ActivitiService activitiService;

	@Autowired
	AccountService accountService;
	@Autowired
	AfterSaleOutHouseService afterSaleOutHouseService;
	@Autowired
	AuditNodeService auditNodeService;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = this.createLayoutView("afterSaleInHouse/inHouseindex");
		List<User> alluser = new ArrayList<User>();
		alluser=userService.userByRole("售后外勤");
		modelAndView.addObject("alluser", alluser);
		return modelAndView;
	}

	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getInHousePage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		String isSubmit=request.getParameter("isSubmit");
		if (isSubmit == null) {
			isSubmit = "";
		}
		if (key == null) {
			key = "";
		}
		List<AfterSaleTicket> afterSaleTickets = afterSaleInHouseService.getInHouseTicket(start, length, key,isSubmit);
		long count = afterSaleTicketService.getTicketRepository().getInHouseCount(key,isSubmit);

		map.put("data", afterSaleTickets);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	//获得一个服务单没有接受的派遣单列表
	@RequestMapping(value = "getoutpage", method = RequestMethod.GET)
	public Map<String, Object> getOutPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String ticketId = request.getParameter("ticketId");
		if (ticketId == null) {
			ticketId = "";
		}
		List<AfterSaleOutHouse> afterSaleOuts = afterSaleOutHouseService.findAllNoRecivedOuts(start, length, ticketId);
		long count = afterSaleOutHouseService.getRepository().allNoReceivedCount(ticketId);

		map.put("data", afterSaleOuts);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 完善服务单页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/perfection", method = RequestMethod.GET)
	public ModelAndView saleChanceDetail(HttpServletRequest request) {
		String type = request.getParameter("type");
		String ticketId = request.getParameter("ticketId");
		ModelAndView modelAndView = null;
		if (type.equals("三包办理")) {
			modelAndView = this.createLayoutView("afterSaleInHouse/newThreeGuarantees");
		} else {
			modelAndView = this.createLayoutView("afterSaleInHouse/inHouseTicketAdd");
		}
		AfterSaleTicket afterSaleTicket = afterSaleTicketService.getTicketRepository().findOne(ticketId);

		// tab2页数据
		List<AfterSaleTicketBack> afterSaleTicketBacks = afterSaleOutHouseService.getRepository()
				.getTicketTab2Data(ticketId);
		// tab3页数据
		List<AfterSaleTicketAdvice> afterSaleTicketAdvices = afterSaleOutHouseService.getRepository()
				.getTicketTab3Data(ticketId);
		AfterSaleTicketBack afterSaleTicketBack = afterSaleTicketBacks.get(0);
		AfterSaleTicketAdvice afterSaleTicketAdvice = afterSaleTicketAdvices.get(0);
		String isGuarantee = afterSaleTicketBack.getIsGuarantee();
		modelAndView.addObject("afterSaleTicket", afterSaleTicket);
		modelAndView.addObject("qualityGuarantee", isGuarantee);
		modelAndView.addObject("afterSaleTicketBack", afterSaleTicketBack);
		modelAndView.addObject("afterSaleTicketAdvice", afterSaleTicketAdvice);

		return modelAndView;
	}

	/**
	 * 三包审批者察看页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/audit-view/{taskId}/{ticketId}", method = RequestMethod.GET)
	public ModelAndView aditorView(@PathVariable String taskId, @PathVariable String ticketId) {
		ModelAndView modelAndView = this.createLayoutView("afterSaleInHouse/guarantee-audit-view");

		AfterSaleTicket afterSaleTicket = afterSaleTicketService.getTicketRepository().findOne(ticketId);

		// tab2页数据
		List<AfterSaleTicketBack> afterSaleTicketBacks = afterSaleOutHouseService.getRepository()
				.getTicketTab2Data(ticketId);
		// tab3页数据
		List<AfterSaleTicketAdvice> afterSaleTicketAdvices = afterSaleOutHouseService.getRepository()
				.getTicketTab3Data(ticketId);
		AfterSaleTicketBack afterSaleTicketBack = afterSaleTicketBacks.get(0);
		AfterSaleTicketAdvice afterSaleTicketAdvice = afterSaleTicketAdvices.get(0);
		String isGuarantee = afterSaleTicketBack.getIsGuarantee();
		modelAndView.addObject("afterSaleTicket", afterSaleTicket);
		modelAndView.addObject("qualityGuarantee", isGuarantee);
		modelAndView.addObject("afterSaleTicketBack", afterSaleTicketBack);
		modelAndView.addObject("afterSaleTicketAdvice", afterSaleTicketAdvice);

		// modelAndView.addObject("quoteName", quote.getName());
		// modelAndView.addObject("quoteId", quote.getId());
		modelAndView.addObject("taskId", taskId);
		modelAndView.addObject("auditnodes",
				auditNodeService.getRepository().getNodesById(afterSaleTicketAdvice.getProcessInstId(), ticketId));
		return modelAndView;
	}

	/**
	 * 三包审批者察看页面JSON
	 * 
	 * @return
	 */
	@RequestMapping(value = "/audit-view/{taskId}/{ticketId}/json", method = RequestMethod.GET)
	public Map<String, Object> aditorViewJSON(@PathVariable String taskId, @PathVariable String ticketId) {
		Map<String, Object> map = new HashMap<>();

		AfterSaleTicket afterSaleTicket = afterSaleTicketService.getTicketRepository().findOne(ticketId);

		// tab2页数据
		List<AfterSaleTicketBack> afterSaleTicketBacks = afterSaleOutHouseService.getRepository()
				.getTicketTab2Data(ticketId);
		// tab3页数据
		List<AfterSaleTicketAdvice> afterSaleTicketAdvices = afterSaleOutHouseService.getRepository()
				.getTicketTab3Data(ticketId);
		AfterSaleTicketBack afterSaleTicketBack = afterSaleTicketBacks.get(0);

		AfterSaleTicketAdvice afterSaleTicketAdvice = afterSaleTicketAdvices.get(0);

		String isGuarantee = afterSaleTicketBack.getIsGuarantee();
		// map.put("afterSaleTicket",afterSaleTicket);
		map.put("qualityGuarantee", isGuarantee);
		map.put("afterSaleTicketBack", afterSaleTicketBack);
		map.put("afterSaleTicketAdvice", afterSaleTicketAdvice);
		map.put("afterSaleTicketPays", afterSaleInHouseService.getTicketPayRepository().findPayDevice(ticketId,
				new PageRequest(0, Integer.MAX_VALUE, Sort.Direction.DESC, "createTime")));

		map.put("taskId", taskId);
		map.put("auditNodes", auditNodeService.getAll(afterSaleTicketAdvice.getProcessInstId(), ticketId));
		return map;
	}

	/**
	 * 三包赔偿零件保存
	 * 
	 * @return
	 */
	@RequestMapping(value = "saveDevice", method = RequestMethod.POST)
	public Map<String, Object> SaveDevice(HttpServletRequest request,
			@RequestBody AfterSaleTicketPay afterSaleTicketPay) {
		Map<String, Object> map = new HashMap<String, Object>();
		afterSaleInHouseService.getTicketPayRepository().save(afterSaleTicketPay);
		map.put("code", 0);
		return map;
	}

	/**
	 * 三包赔偿零件分页
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getPayDevicePage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String ticketId = request.getParameter("ticketId");
		List<AfterSaleTicketPay> afterSaleTicketPay = afterSaleInHouseService.getPayDevice(start, length, ticketId,
				null, null);
		int count = afterSaleTicketPay.size();
		map.put("data", afterSaleTicketPay);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 赔偿零件删除
	 * 
	 * @return
	 */
	@RequestMapping(value = "delete", method = RequestMethod.GET)
	public Map<String, Object> deleteChanceKeyMan(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<AfterSaleTicketPay> payDevices = new ArrayList<AfterSaleTicketPay>();
		for (int i = 0; i < id.length; i++) {
			String payDeviceId = id[i];
			AfterSaleTicketPay payDevice = new AfterSaleTicketPay();
			payDevice.setId(payDeviceId);
			payDevices.add(payDevice);
		}
		afterSaleInHouseService.getTicketPayRepository().deleteInBatch(payDevices);
		map.put("code", 0);
		return map;
	}

	/**
	 * 提交三包审批
	 * 
	 * @param quoteId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/audit/{ticketId}", method = RequestMethod.POST)
	public Map<String, Object> submitAudit(@PathVariable String ticketId, HttpServletRequest request) {

		Map<String, Object> map = new HashMap<>();
		Map<String, String> variables = new HashMap<>();
		Account account = this.getMyAccount();
		int code = -1;
		String unitName = request.getParameter("unitName");
		String auditorNumber = request.getParameter("auditorNumber");
		String auditor1 = request.getParameter("auditor1");
		String auditor2 = request.getParameter("auditor2");
		String auditor3 = request.getParameter("auditor3");
		String auditor4 = request.getParameter("auditor4");
		String auditor5 = request.getParameter("auditor5");
		String auditor6 = request.getParameter("auditor6");
		String auditor7 = request.getParameter("auditor7");
		String auditor8 = request.getParameter("auditor8");

		if (null != ticketId && null != account && null != auditorNumber) {
			// 放置流程实例变量
			variables.put("starter", account.getUser().getId());
			variables.put("auditor1", auditor1);
			variables.put("auditor2", auditor2);
			variables.put("auditor3", auditor3);
			variables.put("auditor4", auditor4);
			variables.put("auditor5", auditor5);
			variables.put("auditor6", auditor6);
			variables.put("auditor7", auditor7);
			variables.put("auditor8", auditor8);

			variables.put("auditorNumber", auditorNumber);
			variables.put("auditState", "已提交");
			variables.put("entityName", "afterSaleInHouse");
			variables.put("processDefinitionName", "三包服务");

			variables.put("entityId", ticketId);

			ProcessInstance pInst = activitiService.startProcessInstance("bid", account.getUser().getId(), variables);
			// 流程启动后，将其实例相关信息保存到业务实体中，以便查询
			afterSaleTicketService.saveProcessStart(ticketId, pInst);
			code = 0;

		}
		map.put("code", code);
		return map;
	}

}
